/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.sf.tomp.slidestobeamer;

import java.io.File;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;

/**
 * SlidesToBeamer: a simple Docbook Slides to LaTeX Beamer source converter
 *
 * @author Tomáš Pitner, tomp@fi.muni.cz
 * @version 0.9

 * Usage: java -jar SlidesToBeamer.jar
 * Note: requires pdflatex, beamer etc. installed
 * Issues:
 * #1 does net cover all db slides elements
 * #2 only UTF-8 is supported for Beamer TeX source
 */
public class Main {

    public static void main(String[] args) throws Exception {

        boolean verbose = false;

        Options options = new Options();
        options.addOption("a", false, "produce TeX article instead of beamer file");
        options.addOption("h", false, "prints this help");
        options.addOption("p", false, "do the beamer for slide presentation (not as handouts)");
        options.addOption("v", false, "be verbose");
        options.addOption("c", false, "cleans up intermediary files (.postxml, .pretex) after processing");
        options.addOption("s", false, "LaTeX Beamer source will only be produced, not compiled");

        options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Docbook Slides source (default: slides.xml)").create("infile"));

        options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("LaTeX Beamer output file (default: [infile].tex)").create("outfile"));

        options.addOption(OptionBuilder.withArgName("name").hasArg().withDescription("LaTeX Beamer theme (default: Warsaw)").create("theme"));

        options.addOption(OptionBuilder.withArgName("name").hasArg().withDescription("beamer/article author (overrides the one from source)").create("author"));

        options.addOption(OptionBuilder.withArgName("text").hasArg().withDescription("beamer/article title (overrides the one from source)").create("title"));

        options.addOption(OptionBuilder.withArgName("text").hasArg().withDescription("beamer/article subtitle (overrides the one conference name and date from source)").create("subtitle"));

        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("v")) {
            verbose = true;
        }

        if (cmd.hasOption("h")) {
            usage(options);

        } else {
            String inFilename = cmd.getOptionValue("infile");
            if (inFilename == null && cmd.getArgs().length > 0) {
                inFilename = cmd.getArgs()[0];
            }
            if (inFilename == null) {
                // nothing to process, so print the usage and exit
                usage(options);
            } else {
                // yeah, we have the input filename
                final File in = new File(inFilename);
                final String inXMLName = in.getName();
                final String prefix = inXMLName.substring(0, inXMLName.lastIndexOf('.'));

                final String postXMLName = prefix + ".postxml";
                final String preTeXName = prefix + ".pretex";
                final String outTeXName = prefix + ".tex";
                final File postXML = new File(in.getParentFile(), postXMLName);
                final File preTeX = new File(in.getParentFile(), preTeXName);
                final File out = cmd.hasOption("outfile") ? new File(cmd.getOptionValue("outfile")) : new File(in.getParentFile(), outTeXName);

                final SlidesToBeamerTransformer transformer = new SlidesToBeamerTransformer();

                if (cmd.hasOption("title")) {
                    transformer.setTitle(cmd.getOptionValue("title"));
                    if (verbose) {
                        System.err.println("Using title: " + transformer.getTitle());
                    }
                }
                if (cmd.hasOption("subtitle")) {
                    transformer.setSubtitle(cmd.getOptionValue("subtitle"));
                    if (verbose) {
                        System.err.println("Using subtitle: " + transformer.getSubtitle());
                    }
                }

                transformer.adjustDocbookSource(in, postXML);
                if (cmd.hasOption("a")) {
                    // produce a LaTeX article file
                    transformer.transformToArticle(postXML, preTeX);
                    if (verbose) {
                        System.err.println("LaTeX 'article' file produced: " + preTeX);
                    }
                } else {
                    // set theme if the option is used
                    final String theme = cmd.getOptionValue("theme");
                    if (theme != null) {
                        transformer.setTheme(theme);
                        if (verbose) {
                            System.err.println("Using theme: " + theme);
                        }
                    }

                    // set author if the option is used
                    final String author = cmd.getOptionValue("author");
                    if (author != null) {
                        transformer.setAuthor(author);
                        if (verbose) {
                            System.err.println("Using author: " + author);
                        }
                    }

                    // presentation instead of handout if the option is used
                    transformer.setHandout(!cmd.hasOption("p"));
                    if (verbose) {
                        System.err.println(cmd.hasOption("p")
                                ? "Producing beamer for presentation."
                                : "Producing beamer for handouts.");
                    }

                    // produce a LaTeX Beamer file
                    transformer.transformToBeamer(postXML, preTeX);
                    if (verbose) {
                        System.err.println("LaTeX 'beamer' file produced: " + preTeX);
                    }
                }
                transformer.adjustLaTeXSource(preTeX, out);
                if (verbose) {
                    System.err.println("LaTeX file adjusted: " + out);
                }

                if (!cmd.hasOption("s")) {
                    transformer.runPDFLaTeX(out);
                    if (verbose) {
                        System.err.println("PDFLaTeX finished: " + out);
                    }
                }

                if (cmd.hasOption("c")) {
                    postXML.deleteOnExit();
                    preTeX.deleteOnExit();
                    if (verbose) {
                        System.err.println("Intermediary files deleted.");
                    }
                }
            }
        }
    }

    private static boolean hasOptionValue(CommandLine cmd, String what) {
        final String optionValue = cmd.getOptionValue(what);
        return optionValue != null && optionValue.length() > 0;
    }

    private static void usage(Options options) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar SlidesToBeamer.jar", options);
    }
}
